package cn.edu.sgu.www.mhxysy.service.impl;

import cn.edu.sgu.www.mhxysy.base.Pager;
import cn.edu.sgu.www.mhxysy.consts.Directories;
import cn.edu.sgu.www.mhxysy.entity.RoleModeling;
import cn.edu.sgu.www.mhxysy.mapper.RoleModelingMapper;
import cn.edu.sgu.www.mhxysy.pager.RoleModelingPager;
import cn.edu.sgu.www.mhxysy.service.RoleModelingService;
import cn.edu.sgu.www.mhxysy.util.UploadUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @author heyunlin
 * @version 1.0
 */
@Service
public class RoleModelingServiceImpl implements RoleModelingService {

	private final UploadUtils uploadUtils;
	private final RoleModelingMapper roleModelingMapper;

	@Autowired
	public RoleModelingServiceImpl(
			UploadUtils uploadUtils,
			RoleModelingMapper roleModelingMapper) {
		this.uploadUtils = uploadUtils;
		this.roleModelingMapper = roleModelingMapper;
	}

	@Override
	public void insert(RoleModeling modeling) {
		modeling.setId(null);

		roleModelingMapper.insert(modeling);
	}

	@Override
	public void updateById(RoleModeling modeling) {
		roleModelingMapper.updateById(modeling);
	}

	@Override
	public List<RoleModeling> selectAll() {
		QueryWrapper<RoleModeling> wrapper = new QueryWrapper<>();

		wrapper.orderByAsc("phyle");

		return roleModelingMapper.selectList(wrapper);
	}

	@Override
	public String selectImageById(Integer id) {
		RoleModeling modeling = selectById(id);

		return modeling != null ? modeling.getImage() : "";
	}

	@Override
	public RoleModeling selectById(Integer id) {
		return roleModelingMapper.selectById(id);
	}

	@Override
	public List<RoleModeling> selectBySex(Integer sex) {
		QueryWrapper<RoleModeling> wrapper = new QueryWrapper<>();

		wrapper.eq(sex != null, "sex", sex);

		return roleModelingMapper.selectList(wrapper);
	}

	@Override
	public List<RoleModeling> selectByPhyle(Integer phyle, Integer gender) {
		QueryWrapper<RoleModeling> wrapper = new QueryWrapper<>();

		wrapper.eq(phyle != null, "phyle", phyle);
		wrapper.eq(gender != null, "sex", gender);

		wrapper.orderByAsc("phyle", "sex");

		return roleModelingMapper.selectList(wrapper);
	}


	@Override
	public Page<RoleModeling> selectByPage(RoleModelingPager pager) {
		QueryWrapper<RoleModeling> wrapper = new QueryWrapper<>();
		Page<RoleModeling> page = Pager.ofPage(pager);

		wrapper.eq(
				pager.getPhyle() != null,
				"phyle", pager.getPhyle()
		);
		wrapper.eq(
				pager.getSex() != null,
				"sex", pager.getSex()
		);

		return roleModelingMapper.selectPage(page, wrapper);
	}

	@Override
	public String upload(MultipartFile file) throws IOException {
		String directory = Directories.DIRECTORY_ROLE;

		return uploadUtils.upload(file, directory);
	}

}